/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.aptech.security;

import com.aptech.business.IAccountManager;
import com.aptech.business.IEventManager;
import com.aptech.domain.model.AccountDO;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


/**
 *
 * @author Admin
 */
public class WebUserDetailsServices implements IWebUserDetailsServices {
    private IAccountManager accountManager;
    private IEventManager eventManager;

    public void reloadUserByUsername(String userName) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        UserDetails user = null;
        AccountDO account = accountManager.getAccountByUsername(username);
        Collection<GrantedAuthority> ga = AuthorityUtils.createAuthorityList("ROLE_USER");
        user = new User(account.getUsername(), account.getPassword(), getAuthorities(false));
        if(account == null) {
            throw new UsernameNotFoundException("User not found!!!");
        }
        return user;
    }
    
    private Collection<GrantedAuthority> getAuthorities(boolean isAdmin) {
            List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
            authList.add(new org.springframework.security.core.authority.GrantedAuthorityImpl("ROLE_USER"));            
            if (isAdmin) {
                    authList.add(new org.springframework.security.core.authority.GrantedAuthorityImpl("ROLE_USER"));
            }
            return authList;
    }

    /**
     * @param accountManager the accountManager to set
     */
    public void setAccountManager(IAccountManager accountManager) {
        this.accountManager = accountManager;
    }
    public void setEventManager(IEventManager eventManager) {
        this.eventManager = eventManager;
    }

}
